package com.mrd;

import com.mrd.gtimp.business.entity.Declaration;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

/**
 * Created by winaya on 2016/9/7.
 */
@Controller
@RequestMapping("/task")
public class TaskAction {
    @Resource
    private RepositoryService repositoryService;

    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;

    @RequestMapping("/publish")
    @ResponseBody
    public String publish() {
        Deployment deployment = repositoryService.createDeployment().addClasspathResource("processes/Order.bpmn").deploy();
        return deployment.getId();
    }


    @RequestMapping("/start")
    @ResponseBody
    public String start(String id) {
//        Map<String, Object> conditions = new HashMap<>();
        Declaration declaration = new Declaration();
        declaration.setId(id);
        declaration.setShip_name("佛航" + id);
        declaration.setState("DS01");
//        conditions.put("declaration", declaration);
        Execution execution = runtimeService.startProcessInstanceByKey("orderProcess", declaration.getId());
        runtimeService.setVariable(execution.getId(), "declaration", declaration);
        return "true";
    }

    @RequestMapping("/complete")
    @ResponseBody
    public String complete(String id) {
        Task task = taskService.createTaskQuery().processInstanceBusinessKey(id).singleResult();
        Declaration declaration = taskService.getVariable(task.getId(), "declaration", Declaration.class);
//        declaration.setState("DS02");
//        declaration.setCustom_time(new Date());
        declaration.setCheck_time(new Date());
        Map<String, Object> map = new HashMap<>();
        map.put("declaration", declaration);
        taskService.complete(task.getId(), map);
        return "true";
    }

    /**
     * 删除流程实例
     * @param instanceId 实例id
     * @return
     */
    @RequestMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable("id") String instanceId){
        runtimeService.deleteProcessInstance(instanceId,"系统删除!");
        return "删除成功!";
    }

    @RequestMapping("/{id}")
    @ResponseBody
    public Task task(@PathVariable("id") String id) {
        Task task = taskService.createTaskQuery().processInstanceBusinessKey(id).singleResult();
        return task;
    }
}
